<!--
  * 合同管理
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-col :span="3">
        <a-form-item label="合同名称" class="smart-query-form-item">
          <a-input v-model:value="queryForm.no" placeholder="输入合同名称" />
        </a-form-item>
      </a-col>
      <a-col :span="3">
        <a-form-item label="一级代理商名称" class="smart-query-form-item">
          <a-input v-model:value="queryForm.no" placeholder="输入一级代理商名称" />
        </a-form-item>
      </a-col>
      <a-col :span="3">
        <a-form-item label="二级代理商名称" class="smart-query-form-item">
          <a-input v-model:value="queryForm.no" placeholder="输入二级代理商名称" />
        </a-form-item>
      </a-col>
      <a-col :span="3">
        <a-form-item label="商户名称" class="smart-query-form-item">
          <a-input v-model:value="queryForm.no" placeholder="输入商户名称" />
        </a-form-item>
      </a-col>
      <a-col :span="3">
        <a-form-item label="签约日期" class="smart-query-form-item">
          <a-date-picker :allowClear="false" :inputReadOnly="true" v-model:value="queryForm.fTime" />
        </a-form-item>
      </a-col>
      <!-- 
      <a-form-item label="状态" class="smart-query-form-item">
        <SmartEnumSelect width="200px" v-model:value="queryForm.status" enum-name="STATUS_ENUM" placeholder="状态" />
      </a-form-item> 
      -->
      <a-col :span="3">
        <a-form-item class="smart-query-form-item">
          <a-button type="primary" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery" class="smart-margin-left10">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-form-item></a-col
      >
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-title">数据列表</div>
      <!-- <div class="smart-table-operate-block">
      </div> -->
      <div class="smart-table-setting-block">
        <a-button @click="downUrl" type="primary" size="small" v-privilege="'trade:insert'">
          <template #icon>
            <CloudDownloadOutlined />
          </template>
          下载
        </a-button>
        <a-button @click="showForm" type="primary" size="small" v-privilege="'trade:insert'">
          <template #icon>
            <PlusOutlined />
          </template>
          添加
        </a-button>
        <!-- <TableOperator v-model="columns" :tableId="null" :refresh="queryData" /> -->
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格begin ----------->
    <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :loading="tableLoading" :pagination="false">
      <template #bodyCell="{ record, column }">
        <!-- <template v-if="column.dataIndex === 'status'">
          <a-switch
            v-privilege="'trade:update_status'"
            :checked="text"
            :checkedValue="1"
            :unCheckedValue="0"
            @change="(checked) => handleStatusChange(checked, record)"
            :loading="record.statusLoading"
          />
        </template> -->
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="view(record)" type="link">详情</a-button
            ><!--  v-privilege="'trade:update'" -->
            <a-button @click="onDelete(record)" type="link">删除</a-button
            ><!--  v-privilege="'trade:update'" -->
            <a-button @click="view(record)" type="link">修改</a-button
            ><!--  v-privilege="'trade:update'" -->
          </div>
        </template>
      </template>
    </a-table>

    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :page_sizeOptions="PAGE_SIZE_OPTIONS"
        :defaultpage_size="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>

    <a-modal title="详情" :width="800" :open="openDetail" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
      <a-form ref="formRef" :model="formData" :rules="rules" :label-col="180" label-align="top">
        <a-row>
          <a-col :span="12">
            <a-form-item label="一级代理商名称" name="type">
              <CustomSelect
                v-model:value="form.chargeId"
                :placeholder="'请选择一级代理商名称'"
                @change="(...data) => changeChargeId(data)"
                :api="chargePage"
                :initParams="{
                  id: form.chargeId,
                }"
                :responseAdapter="resFun"
                value-field="id"
                label-field="label"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="商户名称" name="type">
              <CustomSelect
                v-model:value="form.chargeId"
                :placeholder="'请选择商户名称'"
                @change="(...data) => changeChargeId(data)"
                :api="chargePage"
                :initParams="{
                  id: form.chargeId,
                }"
                :responseAdapter="resFun"
                value-field="id"
                label-field="label"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="合同名称" name="title">
              <a-input v-model:value="formData.title" placeholder="请输入" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="签约日期" name="title">
              <a-date-picker class="w-full" v-model:value="formData.periodEnd" :valueFormat="'YYYY-MM-DD'" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="合同附件" name="title">
              <a-upload
                v-model:file-list="data.shopSignBoardPic"
                name="shopSignBoardPic"
                :max-count="1"
                :custom-request="(file) => uploadFunc(file, 'shopSignBoardPic')"
                :accept="limitUpload['shopSignBoardPic'].fileType.toString()"
                :before-upload="(file, fileList) => beforeUpload(file, fileList, 'shopSignBoardPic')"
                :headers="{
                  authorization: 'authorization-text',
                }"
              >
                <a-button>
                  <upload-outlined />
                  点击上传
                </a-button>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <template #footer>
        <a-space>
          <!-- <a-button @click="onReset">重置</a-button> -->
          <a-button @click="onClose">取消</a-button>
          <a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
        </a-space>
      </template>
    </a-modal>
  </a-card>
</template>
<script setup>
  import { reactive, ref, onMounted, getCurrentInstance } from 'vue'
  import { message, Modal } from 'ant-design-vue'
  import { chargePage, chargeDelete, chargeUpdateStatus } from '/@/api/business/b-operation/channel/charge-api.js'
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const'
  import { smartSentry } from '/@/lib/smart-sentry'
  import TableOperator from '/@/components/support/table-operator/index.vue'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import dayjs from 'dayjs'
  // import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import { selectDictLabel, getObjValue, setObjValue } from '/@/utils/common'
  import {
    CHARGE_TYPE, //计费模式
  } from '/@/constants/dict'
  import { cloneDeep } from 'lodash-es'
  import { myUpload } from '/@/utils/myUpload'

  const { proxy } = getCurrentInstance()

  // ---------------------------- 表格列 ----------------------------
  const columns = ref([
    // {
    //   title: '序号',
    //   dataIndex: 'index',
    //   customRender: ({ index }) => {
    //     return (queryForm.pageNo - 1) * queryForm.pageSize + index + 1
    //   },
    // },
    {
      title: '一级代理商名称',
      dataIndex: 'id',
      ellipsis: true,
    },
    {
      title: '二级代理商名称',
      dataIndex: 'id',
      ellipsis: true,
    },
    {
      title: '商户名称',
      dataIndex: 'settleType',
      ellipsis: true,
    },
    {
      title: '合同编号',
      dataIndex: 'chargeType',
      customRender: ({ text }) => {
        return selectDictLabel(CHARGE_TYPE, text)
      },
      ellipsis: true,
    },
    {
      title: '合同名称',
      dataIndex: 'chargeUserType',
      ellipsis: true,
    },
    {
      title: '签约日期',
      dataIndex: 'cTime',
      customRender: (column) => dayjs(column.text).format('YYYY-MM-DD HH:mm:ss'),
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 200,
    },
  ])
  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    type: undefined, //计费类型
    settleType: undefined, //结算类型
    chargeType: undefined, //计费模式
    chargeUserType: undefined, //计费用户类型
    pageNo: 1,
    pageSize: 10,
  }

  // 查询表单form
  const queryForm = reactive({ ...queryFormState })
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize
    Object.assign(queryForm, queryFormState)
    queryForm.pageSize = pageSize
    queryData()
  }

  // 搜索
  function onSearch() {
    queryForm.pageNo = 1
    queryData()
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    try {
      let queryResult = await chargePage(queryForm)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  onMounted(queryData)

  // 下载模板
  // 模板下载
  const downUrl = async function downUrl() {
    window.open(url, '_blank')
  }
  // 上传附件

  const limitUpload = {
    shopSignBoardPic: {
      fileType: ['.jpg', '.jpeg', '.png', '.bmp', '.gif'],
      fileSize: 5,
    },
  }
  const beforeUpload = (file, fileList, type) => {
    // 校检文件类型
    if (limitUpload[type].fileType.length) {
      const fileExt = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      const isTypeOk = limitUpload[type].fileType.includes(fileExt)
      if (!isTypeOk) {
        message.warning(`文件格式不正确, 请上传${limitUpload[type].fileType.toString().replace(/\./g, '').replace(/,/g, '、')}格式文件!`)
        return false || Upload.LIST_IGNORE
      }
    }

    // 校检文件大小
    if (limitUpload[type].fileSize) {
      const isLt = file.size / 1024 / 1024 < limitUpload[type].fileSize
      if (!isLt) {
        message.warning(`上传文件大小不能超过 ${limitUpload[type].fileSize} MB!`)
        return false || Upload.LIST_IGNORE
      }
    }

    return true
  }

  // 上传文件自定义的方法
  const uploadFunc = async (file, fieldName) => {
    // console.log('file==>', file)
    // 确保获取到文件对象
    const fileObj = file.file
    if (!fileObj) {
      return
    }
    const response = await myUpload(file)
    console.log('response==>', response)
    let arr = getObjValue(formData.value, fieldName).map((item) => {
      if (item.uid === fileObj.uid) {
        message.success(`${fileObj.name} 上传成功`)
        return response
      }
      return item
    })
    setObjValue(formData.value, fieldName, arr)
  }
  // 上传附件
  // 删除
  async function onDelete(record) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除该数据吗?',
      okText: '删除',
      okType: 'danger',
      async onOk() {
        requestBatchDelete(record)
      },
      cancelText: '取消',
      onCancel() {},
    })
  }

  //请求删除
  async function requestBatchDelete(record) {
    try {
      SmartLoading.show()
      const params = {
        id: record.id,
      }
      await userApi.delete(params)
      message.success('删除成功')
      queryData()
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      SmartLoading.hide()
    }
  }
  // 删除
  // 查明细
  const formRef = ref()
  const infoForm = { merchantName: 1 }
  const rules = ref({
    type: [{ required: true, message: '计费类型 必填' }],
    title: [{ required: true, message: '计费名称 必填' }],
  })
  const formData = ref({ ...cloneDeep(infoForm) })
  const openDetail = ref(false)
  function view(row) {
    openDetail.value = true
  }

  function onClose() {
    formData.value = cloneDeep(infoForm)
    // 重置表单的 UI 状态
    formRef.value.resetFields()
    openDetail.value = false
  }

  const validateForm = async () => {
    let isValid = false
    try {
      await formRef.value.validate()
      isValid = true
    } catch (error) {
      message.warning(error.errorFields[0].errors)
      isValid = false
    }
    return isValid
  }
</script>
